
package com.joolun.cloud.pay.api.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joolun.cloud.common.core.config.HomeDirConfigProperties;
import com.joolun.cloud.common.core.util.FileUtils;
import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.common.data.tenant.TenantContextHolder;
import com.joolun.cloud.common.log.annotation.SysLog;
import com.joolun.cloud.common.security.annotation.Inside;
import com.joolun.cloud.pay.api.config.WxPayConfiguration;
import com.joolun.cloud.pay.common.constant.PayConstants;
import com.joolun.cloud.pay.common.entity.PayConfig;
import com.joolun.cloud.pay.api.service.PayConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付配置
 *
 * @author www.joolun.com
 * @date 2020-05-29 16:37:13
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/payconfig")
@Api(value = "payconfig", tags = "支付配置管理")
public class PayConfigController {

    private final PayConfigService payConfigService;
	private final HomeDirConfigProperties homeDirConfigProperties;

    /**
     * 分页列表
     * @param page 分页对象
     * @param payConfig 支付配置
     * @return
     */
    @ApiOperation(value = "分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('payapi:payconfig:index')")
    public R getPage(Page page, PayConfig payConfig) {
        return R.ok(payConfigService.page(page, Wrappers.query(payConfig)));
    }

    /**
     * 支付配置查询
     * @param id
     * @return R
     */
    @ApiOperation(value = "支付配置查询")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('payapi:payconfig:get')")
    public R getById(@PathVariable("id") String id) {
        return R.ok(payConfigService.getById(id));
    }

    /**
     * 支付配置新增
     * @param payConfig 支付配置
     * @return R
     */
    @ApiOperation(value = "支付配置新增")
    @SysLog("新增支付配置")
    @PostMapping
    @PreAuthorize("@ato.hasAuthority('payapi:payconfig:add')")
    public R save(@RequestBody PayConfig payConfig) {
        return R.ok(payConfigService.save(payConfig));
    }

    /**
     * 支付配置修改
     * @param payConfig 支付配置
     * @return R
     */
    @ApiOperation(value = "支付配置修改")
    @SysLog("修改支付配置")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('payapi:payconfig:edit')")
    public R updateById(@RequestBody PayConfig payConfig) {
        return R.ok(payConfigService.updateById(payConfig));
    }

    /**
     * 支付配置删除
     * @param id
     * @return R
     */
    @ApiOperation(value = "支付配置删除")
    @SysLog("删除支付配置")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('payapi:payconfig:del')")
    public R removeById(@PathVariable String id) {
        return R.ok(payConfigService.removeById(id));
    }

	/**
	 * 上传支付证书
	 * @param mulFile
	 * @return
	 */
	@ApiOperation(value = "上传支付证书")
	@PostMapping("/cert/upload")
	public String uploadFile(@RequestParam("file") MultipartFile mulFile) throws IOException {
		File file = FileUtils.multipartFileToFile(mulFile);
		Map<Object, Object> responseData = new HashMap<>();
		String home;
		String os = System.getProperty("os.name");
		if(os.toLowerCase().startsWith("win")){
			home = homeDirConfigProperties.getWindows();
		}else{
			home = homeDirConfigProperties.getLinux();
		}
		String dir = StrUtil.format("{}/{}/{}/", home,"cert", TenantContextHolder.getTenantId());
		File file2 = FileUtil.writeBytes(FileUtil.readBytes(file), dir + file.getName());
		responseData.put("link", file2.getPath());
		return JSONUtil.toJsonStr(responseData);
	}

	/**
	 * 根据支付类型查询支付配置（只返回appId、subAppId）
	 * @param type
	 * @return R
	 */
	@ApiOperation(value = "根据支付类型查询支付配置")
	@GetMapping("/bytype/{type}")
	public R getByType(@PathVariable("type") String type) {
		return R.ok(payConfigService.getOne(Wrappers.<PayConfig>query().lambda()
				.select(PayConfig::getAppId, PayConfig::getSubAppId)
				.eq(PayConfig::getType,type)));
	}

	/**
	 * 支付配置查询
	 * @param appId
	 * @return R
	 */
	@ApiOperation(value = "支付配置查询")
	@GetMapping("/appid/{appId}")
	@Inside
	public R getByAppId(@PathVariable("appId") String appId) {
		return R.ok(payConfigService.findByAppId(appId));
	}
}
